package com.andon.springboot.seed.service.impl;

import com.andon.springboot.seed.api.ApiResponseUtil;
import com.andon.springboot.seed.dao.DeptMapper;
import com.andon.springboot.seed.emum.ApiResponseCode;
import com.andon.springboot.seed.entity.DeptEntity;
import com.andon.springboot.seed.param.DeptParam;
import com.andon.springboot.seed.service.IDeptService;
import com.andon.springboot.seed.util.BeanValidator;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 部门服务实现类
 * </p>
 *
 * @author BWL
 * @since 2018-11-11
 */
@Service
@CacheConfig(cacheNames = "dept", keyGenerator = "keyGenerator")
public class DeptServiceImpl implements IDeptService {

    @Resource
    private DeptMapper deptMapper;


    /**
     * 根据id查询部门名称
     *
     * @param deptId
     * @return ApiResult
     */
    @Override
    @Cacheable
    public ApiResponseUtil<DeptEntity> selectDeptById(Integer deptId) {
        if (deptId == null) {
            return ApiResponseUtil.createByErrorCode(ApiResponseCode.ERROR_PARAM_WRONGFUL);
        }
        DeptEntity deptEntity = deptMapper.selectById(deptId);
        if (deptEntity == null) {
            return ApiResponseUtil.createByErrorCode(ApiResponseCode.ERROR_404);
        }
        return ApiResponseUtil.createBySuccess(deptEntity);
    }

    /**
     * 保存部门信息
     *
     * @param deptParam
     * @return String
     */
    @Override
    @CachePut
    public ApiResponseUtil<String> saveDept(DeptParam deptParam) {
        //校验参数
        String validatorResult = BeanValidator.checkParams(deptParam);
        if (StringUtils.isNotEmpty(validatorResult)) {
            return ApiResponseUtil.createByErrorCode(ApiResponseCode.ERROR_PARAM_WRONGFUL);
        }
        DeptEntity deptEntity = new DeptEntity()
                .setName(deptParam.getDeptName())
                .setOperator(deptParam.getOperator())
                .setRemark(deptParam.getRemark())
                .setSeq(2);
        int rowCount = deptMapper.insert(deptEntity);
        if (rowCount > 0) {
            return ApiResponseUtil.createBySuccess();
        }
        return ApiResponseUtil.createByErrorCode(ApiResponseCode.ERROR_500);
    }
}
